import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  message,
  Tabs,
  Form,
  Input,
  Button,
  Select,
  Checkbox,
  Row,
  Col,
  InputNumber,
  Space,
  Modal,
  Upload
} from 'antd';
import { connect } from 'umi';
import CateComp from '@/components/CategoryComponent';
import { WhseSelect } from '@/components/FormItemSelect';
import request from '@/utils/request';
import ImgQuick from '@/pages/admin/imgQuick';
import UploadUtil from '@/components/UploadUtil';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';

const { TabPane } = Tabs;
const apiURL = '/api/services/app/SysConfig/';
const currentControl = 'SysConfig';
class ViewSysConfig extends React.Component<any, any> {
  constructor(props: Readonly<{}>) {
    super(props);
    this.state = {
      loading: false,
      visible: false,
      checked: false,
      checkedSoMsg: false,
      checkedRcvMsg: false,
      data: {},
      fileList: []
    };
  }
  formRef: any = React.createRef();
  componentDidMount() {
    this.getObj();
  }
  getObj = () => {
    this.setState({ loading: true });
    request(apiURL + 'GetConfig', {
      method: 'GET',
    }).then((response) => {
      if (response.result) {
        let company = response.result
        var fileList: any = [];
        if (company.logo) {
          var obj = {
            uid: company.logo,
            name: company.logo,
            response: {
              result: company.logo,
            },
            status: 'done',
            url: UploadUtil.imgServ + company.logo,
          };
          fileList.push(obj);
        }
        this.formRef.current.setFieldsValue({ company });
        this.setState({ data: company, fileList, logo: company.logo });
      } else {
        message.warning('暂无配置');
      }
      this.setState({ loading: false });
    });
  };
  onFinish = (values: any) => {
    this.setState({ loading: true });
    let act = values.company.id === 0 || !values.company.id ? 'Abp/create' : 'Abp/update';
    values.company.logo = this.state.logo;
    this.props
      .dispatch({
        type: act,
        payload: values.company,
        control: currentControl,
      })
      .then(() => {
        let resp = this.props.response;
        if (resp.result) {
          message.success('保存成功！');
          this.setState({ data: this.props.response.result });
        }
        this.setState({ loading: false });
      });
  };
  clickFun = (val: any) => {
    let fileList = [];
    var obj = {
      uid: val,
      name: val,
      response: {
        result: val,
      },
      status: 'done',
      url: UploadUtil.imgServ + val,
    };
    fileList.push(obj);
    this.setState({
      logo: val,
      fileList,
      visible4: false
    })
  }
  handleUploadList = (info: any) => {
    if (info.file.status === 'done') {
      this.setState({ fileList: info.fileList });
      message.success(`${info.file.name} 上传成功`);
    }
    else {
      this.setState({ fileList: info.fileList });
    }
  };
  render() {
    const { loading, data, fileList, loading2 } = this.state;
    const layout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 19 },
    };
    const uploadButton = (
      <div>
        {loading2 ? <LoadingOutlined /> : <PlusOutlined />}
        <div className="ant-upload-text">上传图片</div>
      </div>
    );
    return (
      <PageHeaderWrapper title={false}>
        <Form {...layout} ref={this.formRef} onFinish={this.onFinish}>
          <Card
            title="系统设置"
            extra={
              <Space>
                <Button type="primary" htmlType="submit" loading={loading}>
                  保存
                </Button>
                <Button type="primary" onClick={this.getObj} loading={loading}>
                  刷新
                </Button>
              </Space>
            }
          >
            <Tabs defaultActiveKey="1">
              <TabPane tab="全局配置" key="1">
                <Row gutter={[16, 16]}>
                  <Col span={12}>
                    <Form.Item name={['company', 'id']} label="ID" hidden>
                      <Input disabled style={{ width: 50 }} />
                    </Form.Item>
                    <Form.Item
                      name={['company', 'companyName']}
                      label="公司名称"
                      rules={[{ required: true, message: '公司名称必填' }]}
                    >
                      <Input style={{ width: 200 }} />
                    </Form.Item>
                    <Form.Item name={['company', 'address']} label="地址">
                      <Input />
                    </Form.Item>
                    <Form.Item name={['company', 'telphone']} label="电话">
                      <Input style={{ width: 200 }} />
                    </Form.Item>
                    <Form.Item name={['company', 'email']} label="邮箱">
                      <Input style={{ width: 200 }} />
                    </Form.Item>
                    <Form.Item name={['company', 'fax']} label="传真">
                      <Input style={{ width: 200 }} />
                    </Form.Item>
                    <Form.Item label="企业图标">
                      <Input.Group compact>
                        <Form.Item>
                          <Upload
                            action={UploadUtil.uploadURL}
                            headers={{
                              Authorization: UploadUtil.accessToken,
                            }}
                            data={{
                              objectId: data?.id,
                              objectName: 'SysConfig',
                              objectField: 'logo',
                            }}
                            listType="picture-card"
                            fileList={fileList}
                            multiple={true}
                            onChange={this.handleUploadList}
                          >
                            {fileList.length >= 1 ? null : uploadButton}
                          </Upload>
                        </Form.Item>
                        <Form.Item>
                          <Button onClick={() => this.setState({ visible4: true })}>选择图片</Button>
                        </Form.Item>
                      </Input.Group>
                    </Form.Item>
                  </Col>
                </Row>
              </TabPane>
              <TabPane tab="财务设置" key="2">
                <Row>
                  <Col span={12}>
                    <Form.Item name={['company', 'costMethod']} label="成本核算方法">
                      <Select style={{ width: 200 }} placeholder="核算方法">
                        <Select.Option key="A" value="A">
                          平均
                        </Select.Option>
                        <Select.Option key="F" value="F">
                          先进先出
                        </Select.Option>
                        <Select.Option key="L" value="L">
                          最后
                        </Select.Option>
                      </Select>
                    </Form.Item>
                    <CateComp
                      layout="Currency"
                      width={200}
                      name={['company', 'baseCurrCode']}
                      label="本币设置"
                    />
                    <CateComp
                      layout="TaxRegion"
                      width={200}
                      name={['company', 'taxRegionCode']}
                      label="应纳税"
                    />
                    <Form.Item name={['company', 'decimalsCost']} label="成本精度">
                      <InputNumber min={0} max={18} />
                    </Form.Item>
                    <Form.Item name={['company', 'decimalsPrice']} label="价格精度">
                      <InputNumber min={0} max={18} />
                    </Form.Item>
                    <Form.Item name={['company', 'decimalsGeneral']} label="一般精度">
                      <InputNumber min={0} max={18} />
                    </Form.Item>
                  </Col>
                </Row>
              </TabPane>
              <TabPane tab="生产设置" key="3">
                <Tabs defaultActiveKey="S1">
                  <TabPane tab="销售" key="S1">
                    <Row>
                      <Col span={12}>
                        <Form.Item name={['company', 'startOrderNum']} label="起始订单号">
                          <Input style={{ width: 200 }} />
                        </Form.Item>
                        <Form.Item
                          name={['company', 'enableSoMsg']}
                          label="启用订单消息"
                          valuePropName="checked"
                        >
                          <Checkbox
                            onChange={(e) => {
                              data.enableSoMsg = e.target.checked;
                              this.setState({ data });
                            }}
                          />
                        </Form.Item>
                        <Form.Item name={['company', 'soMsgTemplate']} label="订单消息模板">
                          <Input disabled={!data.enableSoMsg} />
                        </Form.Item>
                      </Col>
                    </Row>
                  </TabPane>
                  <TabPane tab="工单" key="S2">
                    <Row>
                      <Col span={12}>
                        <Form.Item name={['company', 'jobNumPre']} label="工单号前缀">
                          <Input />
                        </Form.Item>
                        <Form.Item name={['company', 'startJobNum']} label="起始工单号">
                          <InputNumber min={1000} />
                        </Form.Item>
                      </Col>
                      <Col span={12}></Col>
                    </Row>
                  </TabPane>
                  <TabPane tab="质量" key="S3">
                    <Row>
                      <Col span={12}>
                        <Form.Item label="默认检验仓库" style={{ marginBottom: 0 }}>
                          <Input.Group compact>
                            <WhseSelect
                              width={200}
                              showSearch={false}
                              name={['company', 'defInspWhse']}
                              placeholder="仓库"
                            />
                            <Form.Item name={['company', 'defInspBin']}>
                              <Input placeholder="库位" />
                            </Form.Item>
                          </Input.Group>
                        </Form.Item>
                      </Col>
                    </Row>
                  </TabPane>
                  <TabPane tab="仓库" key="S4">
                    <Row>
                      <Col span={12}>
                        <Form.Item label="默认仓库" style={{ marginBottom: 0 }}>
                          <Input.Group compact>
                            <WhseSelect
                              width={200}
                              showSearch={false}
                              name={['company', 'defaultWhse']}
                            />
                            <Form.Item name={['company', 'defaultBin']}>
                              <Input placeholder="库位" />
                            </Form.Item>
                          </Input.Group>
                        </Form.Item>
                        <Form.Item label="默认收货仓库" style={{ marginBottom: 0 }}>
                          <Input.Group compact>
                            <WhseSelect
                              width={200}
                              showSearch={false}
                              name={['company', 'defRcvWhse']}
                              placeholder="仓库"
                            />
                            <Form.Item name={['company', 'defaultRcvBin']}>
                              <Input placeholder="库位" />
                            </Form.Item>
                          </Input.Group>
                        </Form.Item>
                        <Form.Item label="默认出货仓库" style={{ marginBottom: 0 }}>
                          <Input.Group compact>
                            <WhseSelect
                              width={200}
                              showSearch={false}
                              name={['company', 'defShipWhse']}
                              placeholder="仓库"
                            />
                            <Form.Item name={['company', 'defShipBin']}>
                              <Input placeholder="库位" />
                            </Form.Item>
                          </Input.Group>
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item
                          name={['company', 'enableRcvMsg']}
                          label="启用到货提醒"
                          valuePropName="checked"
                        >
                          <Checkbox
                            onChange={(e) => {
                              data.enableRcvMsg = e.target.checked;
                              this.setState({ data });
                            }}
                          />
                        </Form.Item>
                        <Form.Item name={['company', 'rcvMsgTemplate']} label="到货提醒模板">
                          <Input disabled={!data.enableRcvMsg} />
                        </Form.Item>
                      </Col>
                    </Row>
                  </TabPane>
                  <TabPane tab="采购" key="S5">
                    <Row>
                      <Col span={12}>
                        <Form.Item name={['company', 'startPONum']} label="起始PO号">
                          <Input style={{ width: 200 }} />
                        </Form.Item>
                        <Form.Item
                          name={['company', 'enableSugg']}
                          label="启用采购建议"
                          valuePropName="checked"
                        >
                          <Checkbox
                            onChange={(e) => {
                              data.enableSugg = e.target.checked;
                              this.setState({ data });
                            }}
                          />
                        </Form.Item>
                        <Form.Item name={['company', 'suggMsgTemplate']} label="采购建议模板">
                          <Input disabled={!data.enableSugg} />
                        </Form.Item>
                      </Col>
                    </Row>
                  </TabPane>
                </Tabs>
              </TabPane>
              <TabPane tab="MRP设置" key="4">
                <Row>
                  <Col span={22}>
                    <Form.Item name={['company', 'maxMRPTask']} label="允许最大进程">
                      <InputNumber min={1} max={99} />
                    </Form.Item>
                  </Col>
                </Row>
              </TabPane>
            </Tabs>
          </Card>
        </Form>
        <Modal
          title='图片选择'
          visible={this.state.visible4}
          destroyOnClose={true}
          onCancel={() => this.setState({ visible4: false })}
          width={750}
          footer={false}
        >
          <ImgQuick clickFun={(val: any) => this.clickFun(val)} ext='.jpg,.jpeg,.png,.gif' />
        </Modal>
      </PageHeaderWrapper>
    );
  }
}
export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewSysConfig);
